package es.xpt.ysf.view.remoting;

import java.io.IOException;

import javax.el.MethodExpression;
import javax.faces.context.FacesContext;

public class MethodBindingProcessor {

    public void process(FacesContext context, String resourceId) throws IOException {

        // If someone else has completed the response, we do not have
        // anything to do
        if (context.getResponseComplete()) {
            return;
        }

        // Create and execute a method binding based on this resource identifier
        MethodExpression me = mapResourceId(context, resourceId);
        
        me.invoke(context.getELContext(), new Object[] { });

        // Tell JavaServer Faces that the current response has been completed
        context.responseComplete();
    }



    private MethodExpression mapResourceId(FacesContext context, String resourceId) {

        // Strip any leading slash character
        if (resourceId.startsWith("/")) {
            resourceId = resourceId.substring(1);
        }

        // Convert nested slash characters into periods
        resourceId = resourceId.replace('/', '.');

        // Surround the result with "#{" and "}" delimiters
        resourceId = "#{" + resourceId + "}";

        return context.getApplication().getExpressionFactory()
        	.createMethodExpression(context.getELContext(), resourceId, null, new Class[]{});
        

    }

}
